package com.sky.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersCancelDTO;
import com.sky.dto.OrdersPageQueryDTO;
import com.sky.dto.OrdersRejectionDTO;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.entity.AddressBook;
import com.sky.entity.OrderDetail;
import com.sky.entity.Orders;
import com.sky.entity.ShoppingCart;
import com.sky.mapper.AddressBookMapper;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrdersMapper;
import com.sky.mapper.ShoppingCartMapper;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.IAddressBookService;
import com.sky.service.IOrdersService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sky.vo.OrderOverViewVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author fcy
 * @since 2025-09-13
 */
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements IOrdersService {
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;

    /**
     * 用户下单
     * @param ordersSubmitDTO
     * @return
     */
    @Override
    public Result<OrderSubmitVO> submit(OrdersSubmitDTO ordersSubmitDTO) {
        Long userId = BaseContext.getCurrentId();
        AddressBook addressBook = addressBookMapper.selectById(ordersSubmitDTO.getAddressBookId());
        if(addressBook==null){
            throw new RuntimeException("地址有误");
        }
        //查询当前用户购物车
        List<ShoppingCart> shoppingCarts = shoppingCartMapper.selectList(new QueryWrapper<ShoppingCart>().eq("user_id", userId));
        if(shoppingCarts==null||shoppingCarts.size()==0){
            throw new RuntimeException("购物车为空");
        }
        //构造订单数据
        Orders order = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO,order);
        order.setUserId(userId);
        order.setPhone(addressBook.getPhone());
        order.setAddress(addressBook.getDetail());
        order.setConsignee(addressBook.getConsignee());
        order.setNumber(String.valueOf(System.currentTimeMillis()));
        order.setOrderTime(LocalDateTime.now());
        order.setStatus(Orders.PENDING_PAYMENT);
        order.setPayStatus(Orders.UN_PAID);
        ordersMapper.insert(order);
        //构造订单详情数据

        shoppingCarts.forEach(shoppingCart -> {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart,orderDetail);
            orderDetail.setOrderId(order.getId());
            orderDetailMapper.insert(orderDetail);
        });

        //删除购物车数据
        shoppingCartMapper.delete(new QueryWrapper<ShoppingCart>().eq("user_id", userId));
        OrderSubmitVO orderSubmitVO = new OrderSubmitVO();
        orderSubmitVO.setOrderNumber(order.getNumber());
        orderSubmitVO.setOrderAmount(order.getAmount());
        orderSubmitVO.setOrderTime(order.getOrderTime());
        orderSubmitVO.setId(order.getId());
        return Result.success(orderSubmitVO);
    }
    /**
     * 订单查询
     * @param id
     * @return
     */
    @Override
    public Result<OrderVO> getOrderById(Long id) {
        Long userId = BaseContext.getCurrentId();
        Orders orders = this.getById(id);
        
        // 检查订单是否存在
        if (orders == null) {
            return Result.error("订单不存在");
        }
        
        
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders, orderVO);
        List<OrderDetail> orderDetailList = orderDetailMapper.selectList(new QueryWrapper<OrderDetail>().eq("order_id", orders.getId()));
        orderVO.setOrderDetailList(orderDetailList);
        return Result.success(orderVO);
    }
    /**
     * 订单取消
     * @param id
     * @return
     */
    @Override
    public Result cancel(Long id) {
        Long userId = BaseContext.getCurrentId();
        Orders orders = this.getById(id);
        if(orders==null){
            throw new RuntimeException("订单不存在");
        }
        if(!orders.getUserId().equals(userId)){
            throw new RuntimeException("不能取消他人订单");
        }
        if(orders.getStatus()!=Orders.PENDING_PAYMENT){
            throw new RuntimeException("订单不能取消");
        }
        orders.setStatus(Orders.CANCELLED);
        ordersMapper.updateById(orders);
        return Result.success();

    }
    /**
     * 历史订单查询
     * @param pageDto
     * @return
     */
    @Override
    public Result<PageResult> historyOrders(OrdersPageQueryDTO pageDto) {
        //1.构建分页对象
        Page<Orders> page = new Page<>(pageDto.getPage(),pageDto.getPageSize());
        //2.构建查询条件
        Page<Orders> res = lambdaQuery()
                .eq(Orders::getUserId, BaseContext.getCurrentId())
                .eq(pageDto.getStatus()!=null,Orders::getStatus, pageDto.getStatus())
                .page(page);
        List<OrderVO> orderVOList = new ArrayList<>();
        res.getRecords().forEach(orders -> {
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(orders,orderVO);
            List<OrderDetail> orderDetailList = orderDetailMapper.selectList(new QueryWrapper<OrderDetail>().eq("order_id",orders.getId()));
            orderVO.setOrderDetailList(orderDetailList);
            orderVOList.add(orderVO);
        });
        PageResult pageResult = new PageResult();
        pageResult.setTotal(res.getTotal());
        pageResult.setRecords(orderVOList);
        return Result.success(pageResult);




    }
    /**
     * 管理员取消订单
     * @param ordersCancelDTO
     */
    @Override
    public void cancelAdmin(OrdersCancelDTO ordersCancelDTO) {
        Long id = ordersCancelDTO.getId();
        Orders orders = this.getById(id);
        if(orders==null){
            throw new RuntimeException("订单不存在");
        }
        if(orders.getStatus()!=Orders.PENDING_PAYMENT){
            throw new RuntimeException("订单不能取消");
        }
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason(ordersCancelDTO.getCancelReason());
        orders.setCancelTime(LocalDateTime.now());
        ordersMapper.updateById(orders);


    }
    /**
     * 订单统计
     * @return
     */
    @Override
    public OrderOverViewVO statistics() {
        return OrderOverViewVO.builder()
                .waitingOrders(this.count(new QueryWrapper<Orders>().eq("status", Orders.TO_BE_CONFIRMED)))
                .deliveredOrders(this.count(new QueryWrapper<Orders>().eq("status", Orders.DELIVERY_IN_PROGRESS)))
                .completedOrders(this.count(new QueryWrapper<Orders>().eq("status", Orders.COMPLETED)))
                .cancelledOrders(this.count(new QueryWrapper<Orders>().eq("status", Orders.CANCELLED)))
                .allOrders(this.count())
                .build();
    }
    /**
     * 订单完成
     * @param id
     */
    @Override
    public void complete(Long id) {
        Orders orders = this.getById(id);
        if(orders==null){
            throw new RuntimeException("订单不存在");
        }
        if(orders.getStatus()!=Orders.DELIVERY_IN_PROGRESS){
            throw new RuntimeException("订单不能完成");
        }
        orders.setStatus(Orders.COMPLETED);
        ordersMapper.updateById(orders);

    }
    /**
     * 订单拒绝
     * @param ordersRejectionDTO
     */
    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        Long id = ordersRejectionDTO.getId();
        Orders orders = this.getById(id);
        if(orders==null){
            throw new RuntimeException("订单不存在");
        }
        if(orders.getStatus()!=Orders.PENDING_PAYMENT){
            throw new RuntimeException("订单不能拒绝");
        }
        orders.setStatus(Orders.CANCELLED);
        orders.setRejectionReason(ordersRejectionDTO.getRejectionReason());
        ordersMapper.updateById(orders);

    }
    /**
     * 订单确认
     * @param id
     */
    @Override
    public void confirm(Long id) {
        Orders orders = this.getById(id);
        if(orders==null){
            throw new RuntimeException("订单不存在");
        }
        orders.setStatus(Orders.CONFIRMED);
        ordersMapper.updateById(orders);


    }
    /**
     * 订单配送
     * @param id
     */
    @Override
    public void delivery(Long id) {
        Orders orders = this.getById(id);
        if(orders==null){
            throw new RuntimeException("订单不存在");
        }
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);
        ordersMapper.updateById(orders);

    }
    /**
     * 订单搜索
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult searchList(OrdersPageQueryDTO ordersPageQueryDTO) {
        Page<Orders> page = new Page<>(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        Page<Orders> res = lambdaQuery()
                .eq(ordersPageQueryDTO.getStatus()!=null,Orders::getStatus, ordersPageQueryDTO.getStatus())
                .like(ordersPageQueryDTO.getNumber()!=null,Orders::getNumber, ordersPageQueryDTO.getNumber())
                .like(ordersPageQueryDTO.getPhone()!=null,Orders::getPhone, ordersPageQueryDTO.getPhone())
                .between(ordersPageQueryDTO.getBeginTime()!=null&&ordersPageQueryDTO.getEndTime()!=null,Orders::getOrderTime, ordersPageQueryDTO.getBeginTime(), ordersPageQueryDTO.getEndTime())
                .page(page);
        List<OrderVO> orderVOList = new ArrayList<>();
        res.getRecords().forEach(orders -> {
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(orders,orderVO);
            //包含菜品
            List<OrderDetail> orderDetailList = orderDetailMapper.selectList(new QueryWrapper<OrderDetail>().eq("order_id",orders.getId()));
            orderDetailList.forEach(orderDetail -> {
                if(orderDetail.getDishId()!=null){
                    orderVO.setOrderDishes(orderDetail.getName()+"*"+orderDetail.getNumber());
                }
                if(orderDetail.getSetmealId()!=null){
                    orderVO.setOrderDishes(orderDetail.getName()+"*"+orderDetail.getNumber());
                }
                orderVO.setOrderDishes(orderVO.getOrderDishes()+"，");
            });
            orderVOList.add(orderVO);


        });
        PageResult pageResult = new PageResult();
        pageResult.setTotal(res.getTotal());
        pageResult.setRecords(orderVOList);
        return pageResult;


    }
}
